<template>
  <div class="container">
    <div class="add">
      <el-input placeholder="请输入订单号" v-model="search" class="input-with-select">
        <el-button slot="append" icon="el-icon-search" @click="searchF"></el-button>
      </el-input>
      <el-button type="success" @click="getOrderAll">全部订单</el-button>
    </div>
    <el-divider></el-divider>
    <el-table
        :data="tableData"
        stripe
        style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="props">
          <div class="goods" v-for="goods in props.row.selectedCart">
            <div>
              <el-image style="width: 50px; height: 50px;border-radius: 50%;" :src="'http://localhost:7000/file/download?filename='+goods.img[0]"
                        :preview-src-list="goods.img">

              </el-image>
            </div>
            <div class="goods_field">
              {{ goods.goods_name }}
            </div>
            <div class="goods_field">
              ￥{{ goods.goods_price }}
            </div>
            <div class="goods_field">
              x{{goods.num}}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
          prop="_id"
          label="订单号"
          align="center"
      >
      </el-table-column>
      <el-table-column
          prop="userInfo.nickName"
          label="用户昵称"
          align="center"
      >
      </el-table-column>
      <el-table-column
          prop="total"
          label="支付金额/元"
          align="center"
      >
      </el-table-column>
      <el-table-column
          prop="selectedGoodsNum"
          label="商品数量"
          align="center"
      >
      </el-table-column>
      <el-table-column
          prop="order_status"
          label="订单状态"
          align="center"
      >
        <template slot-scope="scope">
          <el-tag size="medium">{{ orderStatus[scope.row.order_status] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="order_add_time"
          label="提交时间"
          align="center"
      >
      </el-table-column>
      <el-table-column
          fixed="right"
          width="150px"
          label="操作"
          align="center"
      >
        <template slot-scope="scope">
          <el-button size="small" type="primary" @click="confirmOrder(scope.row._id,scope.row.userInfo.openid)" :disabled="scope.row.order_status!='payOk'">确认</el-button>
          <el-button size="small" type="danger" @click="refuseOrder(scope.row._id,scope.row.userInfo.openid)" :disabled="scope.row.order_status!='payOk'">拒绝</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="total">
    </el-pagination>
  </div>
</template>

<script>
import {orderStatus} from '@/config/config'
import orderRing from '@/assets/newOrder.mp3'
export default {
  data() {
    return {
      categorys: [],
      search: '',
      //表格数据
      tableData: [],
      //分页变量
      currentPage: 1,
      pageSize: 10,
      total: 0,
      orderStatus,
      socket:'',
    }
  },
  created() {
    this.getOrder()
    this.createWebsocket()
  },
  methods: {
    //确认订单
    confirmOrder(_id,openid){
      this.$confirm(`您确定要接受此订单吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 确定操作
        const req={_id:_id,order_status:'confirm'}
        const result=await this.$http.post(`order/status/update`,req)
        if(result.data.status=="success"){
          this.$message.success("接单成功")
          this.getOrder()
          const send={identity:'admin',identityTo:openid,msg:'商家已接受订单:'+_id}
          console.log(send)
          this.socket.send(JSON.stringify(send))
        }else{
          this.$message.success("接单失败,请稍后重试...")
        }
      }).catch(() => {
        // 取消操作
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    //拒绝订单
    refuseOrder(_id,openid){
      this.$confirm(`您确定拒绝此订单吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 确定操作
        const req={_id:_id,order_status:'reject'}
        const result=await this.$http.post(`order/status/update`,req)
        if(result.data.status=="success"){
          this.$message.success("拒绝成功")
          this.getOrder()
          const send={identity:'admin',identityTo:openid,msg:'商家已拒绝订单:'+_id}
          this.socket.send(JSON.stringify(send))
        }else{
          this.$message.success("拒绝失败,请稍后重试...")
        }
      }).catch(() => {
        // 取消操作
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    //创建websocket连接
    createWebsocket(){
      const that=this;
      if(typeof (WebSocket)=='undefined'){
        that.$notify({
          title:'警告',
          message:'你的浏览器版本太低...',
          type:'warning',
          duration:0
        })
      }else {
        that.socket = new WebSocket("ws://localhost:7000/admin");
        that.socket.onopen = function(e){
          console.log("连接服务器成功");
        }
        that.socket.onclose = function(e){
          console.log("服务器关闭");
        }
        that.socket.onerror = function(){
          console.log("连接出错");
        }
        // 接收服务器的消息
        that.socket.onmessage = function(e){
          that.play()
          console.log(e)
          that.$notify({
            title:'订单消息',
            message:'您有新的外卖订单—订单号:'+e.data,
            type:'warning',
            duration:0
          })
        }
      }
    },
    //播报铃声
    play(){
       const audio=new Audio();
       audio.src=orderRing
       audio.play()
    },
    //search
    searchF() {
      this.currentPage = 1
      this.total = 0
      this.getOrder()
    },
    //获取所有订单
    getOrderAll() {
      this.search = ''
      this.currentPage = 1
      this.getOrder()
    },
    //获取订单列表
    getOrder() {
      const param = {
        params: {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          search: this.search == '' ? '' : (this.search + '$')
        }
      }//$表示搜索的是订单
      this.$http.get('order/getOrderPage', param).then((res) => {
        if (res.data.status == 'success') {
          this.total = res.data.total
          this.tableData = res.data.data
          if (this.tableData.length <= 0 && this.search) {
            this.$message.warning("没有查到相关订单，请确认订单号重试!")
          }
        } else {
          this.$message.warning("数据加载失败...请稍后重试")
        }
      }).catch((err) => {
        this.$message.error("网络错误...")
      })
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val
      //刷新新页
      this.getOrder()
    },
    //跳转添加商品页面
    addGoods() {
      this.$router.push('goodsEdit')
    }
  }
}
</script>
<style lang="scss" scoped>
.container {
  background-color: #fff;
  padding: 10px;

  .add {
    display: flex;

    .el-input {
      width: 500px;
    }

    .el-button {
      margin-left: 30px;
    }
  }
  .goods{
    display: flex;
    align-items: center;
    margin: 10px 0 10px 50px;
    width: 50%;
    .goods_field{
      margin-left: 20px;
    }
  }
}
</style>